import random
import time

import requests
import urllib3
from kdl import Auth

from internal.lib.kdl.client import Client

class KuaidailiProxyToolkit:
    def __init__(self):
        # 其他初始化代码...
        self.kdl_client = Client(Auth(secret_id="你的secret_id", secret_key="你的secret_key"))
        self.request_count = 0
        self.proxy_pool = []  # 代理IP池
        self.current_proxy_index = 0
        self.proxy_expire_time = {}  # 代理有效期记录
    def get_proxy_list(self, num=10):
        """获取私密代理IP列表"""
        try:
            # 最简单的调用，只传必需参数
            proxy_list = self.kdl_client.get_dps(num=num)

            if proxy_list:
                print(f"✅ 成功获取 {len(proxy_list)} 个私密代理IP")
                for i, proxy in enumerate(proxy_list):
                    print(f"   {i + 1}. {proxy}")
            else:
                print("⚠️ 获取到的代理列表为空")

            return proxy_list
        except Exception as e:
            print(f"❌ 获取代理IP失败: {e}")
            return []

    def refresh_proxy_pool(self):
        """刷新代理池"""
        try:
            new_proxies = self.get_proxy_list(10)  # 一次获取5个IP
            if new_proxies:
                self.proxy_pool = new_proxies
                self.current_proxy_index = 0
                print(f"🔄 代理池已刷新，当前有 {len(self.proxy_pool)} 个IP")
            else:
                print("❌ 刷新代理池失败，未获取到有效代理")
        except Exception as e:
            print(f"❌ 刷新代理池失败: {e}")

    def get_current_proxy(self):
        """获取当前要使用的代理"""
        if not self.proxy_pool or self.current_proxy_index >= len(self.proxy_pool):
            self.refresh_proxy_pool()

        if self.proxy_pool:
            proxy = self.proxy_pool[self.current_proxy_index]
            return proxy
        return None

    def rotate_proxy(self):
        """轮换到下一个代理"""
        self.current_proxy_index += 1
        if self.current_proxy_index >= len(self.proxy_pool):
            self.refresh_proxy_pool()

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

import requests
import random
import time
import urllib3
import socket

# 禁用SSL警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def test_proxy_connection(proxy_host, proxy_port, timeout=5):
    """直接测试代理服务器的TCP连接"""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        result = sock.connect_ex((proxy_host, proxy_port))
        sock.close()
        return result == 0  # 返回True表示连接成功
    except:
        return False


def get_current_ip(proxy=None):
    """获取当前公网IP地址"""
    try:
        session = requests.Session()
        session.verify = False
        tunnel = "k542.kdltps.com:15818"
        username = "t16294208494255"
        password = "2rwchvko"
        proxies = {
            "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel},
            "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel}
        }
        # 使用多个IP查询服务，优先使用HTTP协议
        ip_services = [
            'http://ip.3322.net'

        ]
        for service in ip_services:
            try:
                print(f"  尝试服务: {service}")
                response = session.get(
                    service,
                    proxies=proxies
                )
                if response.status_code == 200:
                    ip = response.text.strip()
                    # 验证IP格式
                    if ip and len(ip.split('.')) == 4 and all(part.isdigit() for part in ip.split('.')):
                        return ip
                    else:
                        print(f"  返回内容不是有效IP: {ip}")
            except Exception as e:
                print(f"  服务 {service} 失败: {str(e)[:50]}...")
                continue

        return "所有IP查询服务都失败"

    except Exception as e:
        return f"获取IP失败: {str(e)}"


if __name__ == "__main__":
    print("=" * 50)
    print("代理连接测试")
    print("=" * 50)

    # 先获取本机IP
    print("1. 获取本机IP...")
    th_s = get_current_ip()
    print(f"✅ 当前本机IP：{th_s}")
    # 获取代理
    print("\n2. 获取代理列表...")
